#!/usr/bin/perl
#
use strict;
use lib '/usr/local/netdisco';
use netdisco;
netdisco::config('/usr/local/netdisco/netdisco.conf');

chdir('/usr/local/share/cacti/cli');
$netdisco::SQLCARP = 1;
my $ports = netdisco::sql_rows('device_port,device d1,device d2',
		 ['d1.dns','port','d2.dns as remote_id'],
		{ 'device_port.ip' => \'d1.ip',
		  'd1.dns' => '%Sw%',
		  'd2.ip' => \'device_port.remote_ip',
		  'd2.dns' => '!%Ap%'
		});

my %hostid;

open(HOSTS, "php add_graphs.php --list-hosts|");
while (<HOSTS>) {
	chomp;
	if (/^\s*(\d+)\s*(\S*)\s*(\S*)\s*(\S*)/) {
		my $num = $1;
		my $name = $4;
		$name =~ s/\Q$netdisco::CONFIG{domain}\E//;
		$hostid{lc($name)} = $num;
		print lc($name), " -> ", $num, "\n";
	}
}
close(HOSTS);

# horrible php linkage
my $if_query=`php add_graphs.php --list-snmp-queries | awk '/SNMP - Interface Statistics\$/ { print \$1 }'`;
chomp($if_query);
my $bits=`php add_graphs.php --list-graph-templates | awk '/Interface - Traffic .bits.sec.\$/ { print \$1 }'`;
chomp($bits);
my $bits_qid=`php add_graphs.php --snmp-query-id=$if_query --list-query-types | awk '/In.Out Bits .64-bit Counters.\$/ { print \$1}'`;
chomp($bits_qid);
my $errors=`php add_graphs.php --list-graph-templates | awk '/Interface - Errors.Discards\$/ { print \$1 }'`;
chomp($errors);
my $errors_qid=`php add_graphs.php --snmp-query-id=$if_query --list-query-types | awk '/In.Out Errors.Discarded Packets\$/ { print \$1}'`;
chomp($errors_qid);
foreach my $p (@$ports) {
	my $dev = $p->{dns};
	my $remote = $p->{remote_id};
	my $port = $p->{port};
	$dev =~ s/\Q$netdisco::CONFIG{domain}\E//;
	$remote =~ s/\Q$netdisco::CONFIG{domain}\E//;
	my $hostid = $hostid{lc($dev)};
	print "$dev $hostid $port $remote\n";
	if (not($hostid)) {
		print "- $dev doesn't have a hostid mapping\n";
		next;
	}
	my $cmd = "php add_graphs.php --graph-type=ds --graph-template-id=$bits --host-id=$hostid --snmp-query-id=$if_query --snmp-query-type-id=$bits_qid --snmp-field=ifDescr --snmp-value=\"$port\" --graph-title=\"$dev - $port - link to $remote\"";
	print "+ ", $cmd, "\n";
	system($cmd);
	my $cmd = "php add_graphs.php --graph-type=ds --graph-template-id=$errors --host-id=$hostid --snmp-query-id=$if_query --snmp-query-type-id=$errors_qid --snmp-field=ifDescr --snmp-value=\"$port\" --graph-title=\"$dev - $port - link to $remote - Errors\"";
	print "+ ", $cmd, "\n";
	system($cmd);
}
